package org.finesys.common.core.controller;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.finesys.common.core.util.DateUtils;
import org.finesys.common.core.util.PageUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;

public class BaseController {

    /**
     * 为当前控制器注册一个属性编辑器，只对当前的Controller有效
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        // date类型转换
        webDataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    public void startPage() {
        PageUtils.startPage();
    }

    /**
     * 设置请求分页数据
     */
    public void startPage(Page<?> page) {
        PageUtils.startPage(page);
    }

    /**
     * 返回分页信息
     */
    protected <T> Page<T> getPageInfo(List<T> list) {
        Page<T> page = new Page<>();
        page.setRecords(list);
        page.setTotal(new PageInfo<>(list).getTotal());
        return page;
    }

    /**
     * 返回前端数据
     *
     * @param response web返回对象
     * @param fileName 文件名
     * @param data     文件数据内容
     */
    public void responseZip(HttpServletResponse response, String fileName, byte[] data) throws IOException {
        if (StringUtils.isEmpty(fileName)) {
            fileName = "data.zip";
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment:filename=" + fileName);
        response.setHeader("Content-length", "" + data.length);
        response.setContentType("application/octet-stream;charset:UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
